package com.letianpai.activity.home;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.letianpai.R;
import com.letianpai.activity.HeadPictureActivity2;
import com.letianpai.activity.TabGroupActivity;
import com.letianpai.activity.family.FamilyListActivity;
import com.letianpai.application.ManageApplication;
import com.letianpai.bean.BackResponse;
import com.letianpai.db.Constant;
import com.letianpai.db.cache.UserCache;
import com.letianpai.dialog.CustomDialog;
import com.letianpai.http.RequestBean.UserInformation;
import com.letianpai.http.RequestBean.UserInformationBean;
import com.letianpai.utils.ChatUtils;
import com.letianpai.utils.ImageTools;
import com.letianpai.utils.JsonUtil;
import com.letianpai.utils.XmppTool;

public class SetDetailActivity extends Activity implements OnClickListener {
	View head, name_statu, sex_notify, birth_notify, pwd, headBackText;
	TextView family_status_number, family_status_pwd, unlogin,
			family_status_text, family_day_text, family_sex_text;
	static ImageView image;
	static ContentResolver cr;
	RadioGroup sex;
	TextView headShare, headText;
	RadioButton male, female;
	int temp = 1;
	private Dialog dialog3;
	ProgressDialog pd;
	RequestQueue requestQueue;
	SharedPreferences sp;
	Editor editor;
	public static Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case 0:
				Log.i("info", "相机");
				Bitmap bm = (Bitmap) msg.getData().get("data");
				SetDetailActivity.image.setImageBitmap(bm);
				Boolean ishead0 = ChatUtils.changeImage(bm);
				FamilyListActivity.mb = bm;
				Log.i("info", ishead0 + "hahahaha");

				break;
			case 1:
				Log.i("info", "相册");
				Uri uri = Uri.parse((String) msg.getData().get("a"));
				Cursor cursor = cr.query(uri, null, null, null, null);
				cursor.moveToFirst();

				Bitmap bitmap = null;
				try {
					bitmap = BitmapFactory
							.decodeStream(cr.openInputStream(uri));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				SetDetailActivity.image.setImageBitmap(bitmap);
				FamilyListActivity.mb = bitmap;
				Boolean ishead1 = ChatUtils.changeImage(bitmap);
				break;
			case 2:
				Log.i("info", "图片");
				int pictureId = (Integer) msg.getData().get("picture");
				SetDetailActivity.image.setImageResource(pictureId);
				Bitmap bm2 = ImageTools
						.drawableToBitmap(SetDetailActivity.image.getDrawable());
				Boolean ishead2 = ChatUtils.changeImage(bm2);
				FamilyListActivity.mb = bm2;
				break;

			default:
				break;
			}

		}

	};
	private String day;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ManageApplication.getInstance().addActivity(this);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.set_detail);
		sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);
		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}
		cr = this.getContentResolver();
		head.setOnClickListener(this);
		name_statu.setOnClickListener(this);
		sex_notify.setOnClickListener(this);
		birth_notify.setOnClickListener(this);
		pwd.setOnClickListener(this);
	}

	private void init() throws Exception {
		headShare = (TextView) findViewById(R.id.headShare);
		headShare.setText("");
		headText = (TextView) findViewById(R.id.headText);
		headText.setText("我的资料");
		headBackText = findViewById(R.id.headBackText);
		headBackText.setOnClickListener(this);
		head = findViewById(R.id.basic);
		name_statu = findViewById(R.id.family_status);
		sex_notify = findViewById(R.id.newmsg_notify);
		birth_notify = findViewById(R.id.voice_notify);
		pwd = findViewById(R.id.retrieval);
		image = (ImageView) findViewById(R.id.pic);
		family_status_number = (TextView) findViewById(R.id.family_status_number);
		family_status_pwd = (TextView) findViewById(R.id.family_status_pwd);
		family_status_text = (TextView) findViewById(R.id.family_status_text);
		family_day_text = (TextView) findViewById(R.id.family_day_text);
		family_sex_text = (TextView) findViewById(R.id.family_sex_text);
		if (null!=FamilyListActivity.ui.getSex()&&"2".equals(FamilyListActivity.ui.getSex())) {
			family_sex_text.setText("女");

		} else if (null!=FamilyListActivity.ui.getSex()&&"1".equals(FamilyListActivity.ui.getSex())) {
			family_sex_text.setText("男");
		}
		requestQueue = Volley.newRequestQueue(this);
		family_day_text.setText(FamilyListActivity.ui.getBirthdate());

		family_status_number.setText(sp.getString("username", "null"));

		family_status_pwd.setText(sp.getString("password", "null"));
		unlogin = (TextView) findViewById(R.id.unlogin);
		unlogin.setOnClickListener(this);
		Bitmap bm = FamilyListActivity.mb;
		if (null != bm) {
			SetDetailActivity.image.setImageBitmap(bm);
		}
		;
		String nickname = FamilyListActivity.nickname;
		if (nickname != null) {
			family_status_text.setText(nickname);
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.basic:
			Intent intent_b = new Intent(this, HeadPictureActivity2.class);
			startActivityForResult(intent_b, 1);
			break;
		case R.id.family_status:
			final CustomDialog dialog = new CustomDialog(this,
					R.layout.setting_namedialog);
			dialog.setLeftOnClick(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String name = dialog.editview.getText().toString();
					Log.i("info", name + "");
					boolean isname = ChatUtils.changename(XmppTool.getConnection(), name);
					Log.i("info", isname + "");
					if (isname) {
						family_status_text.setText(name);
						FamilyListActivity.nickname = name;
					}
					dialog.dismiss();
				}
			});
			dialog.setRightOnClick(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
			break;
		case R.id.newmsg_notify:
			dialog3 = new Dialog(this, R.style.customDialog);
			Window window = dialog3.getWindow();
			window.setContentView(R.layout.setting_sexdialog);
			WindowManager wm = (WindowManager) this
					.getSystemService(Context.WINDOW_SERVICE);
			Display display = wm.getDefaultDisplay();
			CustomDialog.setDialogAttributes(dialog3, display, 0.95);
			selectSex(dialog3);
			dialog3.show();
			postSex(temp);
			break;
		case R.id.voice_notify:

			Intent intent = new Intent(this, MyDaySetting.class);
			intent.putExtra("username", sp.getString("username", ""));
			startActivityForResult(intent, 1);

			break;
		case R.id.retrieval:
			final CustomDialog dialog2 = new CustomDialog(this,
					R.layout.setting_pwddialog);
			dialog2.setLeftOnClick(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String pwd = dialog2.editview.getText().toString();
					boolean issuccess = ChatUtils.changePassword(
							XmppTool.getConnection(), pwd);
					if (issuccess) {
						family_status_pwd.setText(pwd);
					}
					dialog2.dismiss();
				}
			});
			dialog2.setRightOnClick(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog2.dismiss();
				}
			});
			dialog2.show();
			break;
		case R.id.unlogin:
			pd = new ProgressDialog(SetDetailActivity.this);
			pd.setTitle("注销请稍等...");
			pd.show();
			pd.setCanceledOnTouchOutside(false);
			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean flag = XmppTool.closeConnection();
					if (flag == true) {
						handle.sendEmptyMessage(1);// 成功
					} else {
						handle.sendEmptyMessage(2);// 失败
					}
				}
			}).start();

			break;
		case R.id.headBackText:
			finish();
			break;
		default:
			break;

		}
	}

	private void selectSex(Dialog dialog3) {
		sex = (RadioGroup) dialog3.findViewById(R.id.sex);
		male = (RadioButton) dialog3.findViewById(R.id.male);
		female = (RadioButton) dialog3.findViewById(R.id.female);
		sex.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				if (R.id.male == arg1) {
					temp = 1;
					male.setBackgroundResource(R.drawable.sex_selected);
					male.setTextColor(getResources().getColor(R.color.white));
					female.setBackgroundResource(R.drawable.sex_select);
					female.setTextColor(getResources().getColor(R.color.gray));
					family_sex_text.setText("男");
				} else if (R.id.female == arg1) {
					temp = 2;
					male.setBackgroundResource(R.drawable.sex_select);
					male.setTextColor(getResources().getColor(R.color.gray));
					female.setBackgroundResource(R.drawable.sex_selected);
					female.setTextColor(getResources().getColor(R.color.white));
					Log.i("info", temp + "性别");
					family_sex_text.setText("女");
				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 1) {
			Bundle b = data.getExtras();
			day = b.getString("day");
			family_day_text.setText(day);
		}
	}

	// 修改性别
	public void postSex(int temp) {
		Map<String, String> map = new HashMap<String, String>();
		UserInformation userInfo = new UserInformation();
		userInfo.setUsername(sp.getString("username", "null"));
		userInfo.setSex(temp);
		Log.d("zzzz", userInfo.getUsername());
		UserInformationBean user = new UserInformationBean();
		user.setHead("changeUserInfoServlet");
		user.setContent(userInfo);
		// msg值
		String msg = JsonUtil.objectToString(user, UserInformationBean.class);
		String url = Constant.URL + "?msg=" + msg;
		Log.d("zzzz", url);
		map.put("msg", msg);
		StringRequest request = new StringRequest(url, new ls(), new el());
		requestQueue.add(request);
	}

	class ls implements Listener<String> {

		@Override
		public void onResponse(String arg0) {
			BackResponse br = (BackResponse) JsonUtil.StringToObject(arg0,
					BackResponse.class);
			Toast.makeText(SetDetailActivity.this, br.getMessage(),
					Toast.LENGTH_SHORT).show();
			if (br.getStatus().equals("SUCCESS")) {
				Toast.makeText(SetDetailActivity.this, br.getMessage(),
						Toast.LENGTH_SHORT).show();
				// LoginActivity.ui.setSex(sex);
			}

		}

	}

	class el implements ErrorListener {

		@Override
		public void onErrorResponse(VolleyError arg0) {
			Toast.makeText(SetDetailActivity.this, "请求失败", Toast.LENGTH_SHORT)
					.show();
		}

	}

	public Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				// 退出系统
				ManageApplication.getInstance().unLogin();
				UserCache.getInstance().modifyLogin(SetDetailActivity.this,
						false);
				Intent intent1 = new Intent(SetDetailActivity.this,
						HomeMainActivity.class);
				Window w = TabGroupActivity.group_activity
						.getLocalActivityManager().startActivity("login",
								intent1);
				View view = w.getDecorView();
				editor = sp.edit();
				editor.putString("islogin", "1");
				editor.putString("username", "1");
				editor.commit();
				TabGroupActivity.group_activity.setContentView(view);
				pd.dismiss();

				break;
			case 2:
				Toast.makeText(SetDetailActivity.this, "注销失败请检查网络",
						Toast.LENGTH_SHORT).show();
				pd.dismiss();
				break;
			default:
				break;
			}
		}
	};
}
